import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart';
import '../../core/api_response.dart';
import '../../services/auth_service.dart';
import '../../models/user.dart';
import '../../models/auth_token.dart';
import '../../models/login_request.dart';
import '../auth_repository.dart';

class ApiAuthRepository implements AuthRepository {
  final AuthService _authService;
  static const String _tokenKey = 'auth_token';
  static const String _userKey = 'auth_user';

  ApiAuthRepository({AuthService? authService})
      : _authService = authService ?? AuthService();

  @override
  Future<ApiResponse<LoginResponse>> login(LoginRequest request) async {
    final response = await _authService.login(request);
    
    if (response.isSuccess && response.data != null) {
      // 保存 Token 和用户信息
      await saveToken(response.data!.token);
      await saveUser(response.data!.user);
    }
    
    return response;
  }

  @override
  Future<ApiResponse<User>> register(RegisterRequest request) async {
    return await _authService.register(request);
  }

  @override
  Future<ApiResponse<void>> logout() async {
    final response = await _authService.logout();
    
    // 无论服务端登出是否成功，都清理本地数据
    await clearToken();
    await clearUser();
    
    return response;
  }

  @override
  Future<ApiResponse<void>> forgotPassword(ForgotPasswordRequest request) async {
    return await _authService.forgotPassword(request);
  }

  @override
  Future<ApiResponse<AuthToken>> refreshToken(String refreshToken) async {
    final response = await _authService.refreshToken(refreshToken);
    
    if (response.isSuccess && response.data != null) {
      // 保存新的 Token
      await saveToken(response.data!);
    }
    
    return response;
  }

  @override
  Future<AuthToken?> getStoredToken() async {
    try {
      final prefs = await SharedPreferences.getInstance();
      final tokenJson = prefs.getString(_tokenKey);
      
      if (tokenJson != null) {
        final tokenMap = jsonDecode(tokenJson) as Map<String, dynamic>;
        return AuthToken.fromJson(tokenMap);
      }
      
      return null;
    } catch (e) {
      print('❌ [AUTH_REPOSITORY] 获取存储的Token失败: $e');
      return null;
    }
  }

  @override
  Future<void> saveToken(AuthToken token) async {
    try {
      final prefs = await SharedPreferences.getInstance();
      final tokenJson = jsonEncode(token.toJson());
      await prefs.setString(_tokenKey, tokenJson);
      print('✅ [AUTH_REPOSITORY] Token保存成功');
    } catch (e) {
      print('❌ [AUTH_REPOSITORY] Token保存失败: $e');
    }
  }

  @override
  Future<void> clearToken() async {
    try {
      final prefs = await SharedPreferences.getInstance();
      await prefs.remove(_tokenKey);
      print('🗑️ [AUTH_REPOSITORY] Token已清除');
    } catch (e) {
      print('❌ [AUTH_REPOSITORY] Token清除失败: $e');
    }
  }

  @override
  Future<ApiResponse<User>> getProfile() async {
    return await _authService.getProfile();
  }

  @override
  Future<ApiResponse<User>> updateProfile(User user) async {
    final response = await _authService.updateProfile(user);
    
    if (response.isSuccess && response.data != null) {
      // 更新本地存储的用户信息
      await saveUser(response.data!);
    }
    
    return response;
  }

  @override
  Future<User?> getStoredUser() async {
    try {
      final prefs = await SharedPreferences.getInstance();
      final userJson = prefs.getString(_userKey);
      
      if (userJson != null) {
        final userMap = jsonDecode(userJson) as Map<String, dynamic>;
        return User.fromJson(userMap);
      }
      
      return null;
    } catch (e) {
      print('❌ [AUTH_REPOSITORY] 获取存储的用户信息失败: $e');
      return null;
    }
  }

  @override
  Future<void> saveUser(User user) async {
    try {
      final prefs = await SharedPreferences.getInstance();
      final userJson = jsonEncode(user.toJson());
      await prefs.setString(_userKey, userJson);
      print('✅ [AUTH_REPOSITORY] 用户信息保存成功: ${user.username}');
    } catch (e) {
      print('❌ [AUTH_REPOSITORY] 用户信息保存失败: $e');
    }
  }

  @override
  Future<void> clearUser() async {
    try {
      final prefs = await SharedPreferences.getInstance();
      await prefs.remove(_userKey);
      print('🗑️ [AUTH_REPOSITORY] 用户信息已清除');
    } catch (e) {
      print('❌ [AUTH_REPOSITORY] 用户信息清除失败: $e');
    }
  }

  @override
  Future<bool> isLoggedIn() async {
    final token = await getStoredToken();
    final user = await getStoredUser();
    return token != null && user != null && !token.isExpired;
  }

  @override
  Future<bool> hasValidToken() async {
    final token = await getStoredToken();
    return token != null && !token.isExpired;
  }
}